import React, {Component} from 'react';
import {FlatList, View} from 'react-native';
import {globalStore} from "../../libs/ShareStore";
import {listViewStyle} from "./style/listViewStyle";
import RoomAddListData from "../../model/item/RoomAddListData";
import RoomAddListItem from "./item/RoomAddListItem";
import Beans from "../../libs/sdk/echatim/common/utils";
import {FriendToAddRoomStore} from "../../model/store/FriendToAddRoomStore";
import EButton from "../utils/EButton";


type RoomAddListStateType = {
    items:Array<RoomAddListData>,
    refreshing:boolean,
}

export default class RoomAddListView extends Component<any, RoomAddListStateType> {
    private itemSelected:any = {};

    constructor(props) {
        super(props);
        // 初始数据为所有的朋友
        const initFriendList = globalStore.friendList.map(function (v) {
            const data = Beans.to(v);
            data.id = data.auid;
            return data;
        });
        this.state = {
            items:initFriendList,
            refreshing: false
        };
    }

    componentDidMount(): void {

    }

    onSelectItem(select:boolean, data:RoomAddListData){
        if(select){
            this.itemSelected[data.id] = data;
        }
        else {
            delete this.itemSelected[data.id];
        }
        globalStore.friendToAddRoomList = Object.values(this.itemSelected).map(v => {
            const data = new FriendToAddRoomStore();
            data.auid = (v as RoomAddListData).id;
            data.name = (v as RoomAddListData).name;
            data.select = 1;
            return data;
        });

        console.log(`now selected item:` + Beans.json(Object.values(globalStore.friendToAddRoomList)));
    }

    onAddRoom():void{
        globalStore.onAddRoomPressOk()
    }

    render() {
        return (
            <View style = {listViewStyle.container}>
                <View style={listViewStyle.list}>
                    <FlatList
                        extraData = {this.state.refreshing}
                        data = {this.state.items}
                        renderItem = {({item})=><RoomAddListItem data={item}  avatar={item.avatar}   name={item.name} onSelect={(v, data)=>this.onSelectItem(v, data)} />}
                    />
                </View>

                <EButton title={'添加群'} onPress={()=>{this.onAddRoom()}}/>
            </View>
        );
    }
}

